/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.scene.domain.*;
import com.koron.scene.mapper.*;
import com.koron.scene.service.api.ProjectService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;
import com.koron.scene.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.koron.scene.service.impl.DeviceServiceImpl.checkObjAllFieldsIsNull;
import static com.koron.scene.utils.ExcelUtil.getCellValue;

@Service
public class ProjectServiceImpl implements ProjectService {

    private static final Logger logger = LoggerFactory.getLogger(ProjectServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private Util util;

    MessageBean<Project> checkAndBuildProject(String name, String corpCode, String corpName, String projectType,
                                              String projectLeaderCode, String projectLeaderName, String establishDateStr, Integer state,
                                              String description) {
        MessageBean<Project> messageBean = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Project.class);
        Project project = new Project();
        if (StringUtils.isBlank(name)) {
            messageBean.setCode(BusinessCode.PROJECT_NAME_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_NAME_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (StringUtils.isBlank(corpCode)) {
            messageBean.setCode(BusinessCode.PROJECT_CORP_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_CORP_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (StringUtils.isBlank(corpName)) {
            messageBean.setCode(BusinessCode.PROJECT_CORP_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_CORP_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (StringUtils.isBlank(projectType)) {
            messageBean.setCode(BusinessCode.PROJECT_TYPE_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_TYPE_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (StringUtils.isBlank(projectLeaderCode)) {
            messageBean.setCode(BusinessCode.PROJECT_LEADER_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_LEADER_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (StringUtils.isBlank(projectLeaderName)) {
            messageBean.setCode(BusinessCode.PROJECT_LEADER_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_LEADER_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        if (state == null) {
            messageBean.setCode(BusinessCode.PROJECT_STATE_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_STATE_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        Date establishDate = DateUtil.formatStringToDate(establishDateStr, DateUtil.DATE_FORMAT_YMD);
        if (establishDate == null) {
            messageBean.setCode(BusinessCode.PROJECT_ESTABLISHDATE_CANNOT_EMPTY.getCode());
            messageBean.setDescription(BusinessCode.PROJECT_ESTABLISHDATE_CANNOT_EMPTY.getDescription());
            return messageBean;
        }
        project.setName(name);
        project.setCorpCode(corpCode);
        project.setCorpName(corpName);
        project.setProjectType(projectType);
        project.setProjectLeaderCode(projectLeaderCode);
        project.setProjectLeaderName(projectLeaderName);
        project.setEstablishDate(establishDate);
        project.setState(state);
        project.setDescription(description);
        messageBean.setData(project);
        return messageBean;
    }

    @Override
    public MessageBean<?> add(StaffBean user, MultipartFile[] files, String name, String corpCode, String corpName, String projectType,
                              String projectLeaderCode, String projectLeaderName, String establishDateStr, Integer state,
                              String description, String projectEnterpriseListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        List<String> pathList = new ArrayList<>();
        List<String> prePathList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            ProjectEnterpriseMapper projectEnterpriseMapper = factory.getMapper(ProjectEnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            MessageBean<Project> messageBean = checkAndBuildProject(name, corpCode, corpName, projectType, projectLeaderCode,
                    projectLeaderName, establishDateStr, state, description);
            if (messageBean == null || messageBean.getCode() != 0) {
                return messageBean;
            }
            Project project = messageBean.getData();

            List<Project> exitList = projectMapper.findProjectByName(name, corpCode);
            if (exitList != null && exitList.size() > 0) {
                msg.setCode(BusinessCode.PROJECT_NAME_CANNOT_DUP.getCode());
                msg.setDescription(BusinessCode.PROJECT_NAME_CANNOT_DUP.getDescription());
                return msg;
            }

            BaseEntityUtil.setAddBaseProperties(project, user);
            //解析项目相关方
            List<ProjectEnterprise> projectEnterpriseList = new ArrayList<>();
            List<ProjectMaintainStaff> projectMaintainStaffList = new ArrayList<>();
            if (StringUtils.isNotBlank(projectEnterpriseListStr)) {
                List<Enterprise> enterpriseList = JSONObject.parseArray(projectEnterpriseListStr, Enterprise.class);
                if (enterpriseList != null && enterpriseList.size() > 0) {
                    for (Enterprise enterprise : enterpriseList) {
                        ProjectEnterprise projectEnterprise = new ProjectEnterprise();
                        if (StringUtils.isBlank(enterprise.getId())) {
                            msg.setCode(BusinessCode.PROJECT_ENTERPRISE_CANNOT_EMPTY.getCode());
                            msg.setDescription(BusinessCode.PROJECT_ENTERPRISE_CANNOT_EMPTY.getDescription());
                            return msg;
                        }
                        projectEnterprise.setProjectId(project.getId());
                        projectEnterprise.setEnterpriseId(enterprise.getId());
                        BaseEntityUtil.setAddBaseProperties(projectEnterprise, user);
                        projectEnterpriseList.add(projectEnterprise);
                        List<ProjectMaintainStaff> staffs = enterprise.getStaffList();
                        if (staffs != null && staffs.size() > 0) {
                            for (ProjectMaintainStaff staff : staffs) {
                                if (StringUtils.isBlank(staff.getStaffCode()) || StringUtils.isBlank(staff.getStaffName())) {
                                    msg.setCode(BusinessCode.PROJECT_MAINTAIN_STAFF_CANNOT_EMPTY.getCode());
                                    msg.setDescription(BusinessCode.PROJECT_MAINTAIN_STAFF_CANNOT_EMPTY.getDescription());
                                    return msg;
                                }
                                staff.setEnterpriseId(enterprise.getId());
                                staff.setProjectId(project.getId());
                                BaseEntityUtil.setAddBaseProperties(staff, user);
                                projectMaintainStaffList.add(staff);
                            }
                        }
                    }
                }
            }
            //保存附件
            if (files != null && files.length > 0) {
                for (MultipartFile file : files) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(file);
                        String filPath = url + "#" + file.getOriginalFilename();
                        pathList.add(filPath);
//                        File pdfFile = DocConverterUtils.converter(file);
                        String pdfPath = docConverterUtils.converterUpdate(file);
                        if (pdfPath != null) {
//                            String pdfFilePath = clientWrapper.uploadFile(new FileInputStream(pdfFile), pdfFile.length(), FilenameUtils.getExtension(pdfFile.getName()));
                            prePathList.add(pdfPath);
                        } else {
                            prePathList.add(filPath);
                        }
                    }
                }
                project.setAttachment(pathList.size() <= 0 ? null : new Gson().toJson(pathList));
                project.setPreviewAttachment(prePathList.size() <= 0 ? null : new Gson().toJson(prePathList));
            }
            projectMapper.insert(project);
            if (projectEnterpriseList != null && projectEnterpriseList.size() > 0) {
                projectEnterpriseMapper.insertList(projectEnterpriseList);
            }
            if (projectMaintainStaffList != null && projectMaintainStaffList.size() > 0) {
                maintainStaffMapper.insertList(projectMaintainStaffList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            if (pathList != null && pathList.size() > 0) {
                for (String p : pathList) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            if (prePathList != null && prePathList.size() > 0) {
                for (String p : prePathList) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> update(StaffBean user, MultipartFile[] files, String projectId, String name, String corpCode, String corpName,
                                 String projectType, String projectLeaderCode, String projectLeaderName, String establishDateStr,
                                 Integer state, String description, String projectEnterpriseListStr,
                                 String keepPathListStr, String deletePathListStr, String keepPrePathListStr, String deletePrePathListStr) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            ProjectEnterpriseMapper projectEnterpriseMapper = factory.getMapper(ProjectEnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            if (StringUtils.isBlank(projectId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            Project oldProject = projectMapper.selectByPrimaryKey(projectId);
            if (oldProject == null) {
                msg.setCode(BusinessCode.PROJECT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.PROJECT_NOT_EXIST.getDescription());
                return msg;
            }
            MessageBean<Project> messageBean = checkAndBuildProject(name, corpCode, corpName, projectType, projectLeaderCode,
                    projectLeaderName, establishDateStr, state, description);
            if (messageBean == null || messageBean.getCode() != 0) {
                return messageBean;
            }
            Project project = messageBean.getData();
            List<Project> exitList = projectMapper.findProjectByName(name, corpCode);
            if (exitList != null && exitList.size() > 0) {
                List<Project> list = exitList.stream().filter(p -> !p.getId().equals(projectId)).collect(Collectors.toList());
                if (list != null && !list.isEmpty()) {
                    msg.setCode(BusinessCode.PROJECT_NAME_CANNOT_DUP.getCode());
                    msg.setDescription(BusinessCode.PROJECT_NAME_CANNOT_DUP.getDescription());
                    return msg;
                }
            }
            project.setId(projectId);
            BaseEntityUtil.setUpdateBaseProperties(project, user);
            //解析项目相关方
            List<ProjectEnterprise> projectEnterpriseList = new ArrayList<>();
            List<ProjectMaintainStaff> projectMaintainStaffList = new ArrayList<>();
            if (StringUtils.isNotBlank(projectEnterpriseListStr)) {
                List<Enterprise> enterpriseList = JSONObject.parseArray(projectEnterpriseListStr, Enterprise.class);
                List<String> eidList = new ArrayList<>();
                if (enterpriseList != null && enterpriseList.size() > 0) {
                    for (Enterprise enterprise : enterpriseList) {
                        ProjectEnterprise projectEnterprise = new ProjectEnterprise();
                        if (StringUtils.isBlank(enterprise.getId())) {
                            msg.setCode(BusinessCode.PROJECT_ENTERPRISE_CANNOT_EMPTY.getCode());
                            msg.setDescription(BusinessCode.PROJECT_ENTERPRISE_CANNOT_EMPTY.getDescription());
                            return msg;
                        }
                        if (!eidList.contains(enterprise.getId())) {
                            eidList.add(enterprise.getId());
                            projectEnterprise.setProjectId(project.getId());
                            projectEnterprise.setEnterpriseId(enterprise.getId());
                            BaseEntityUtil.setAddBaseProperties(projectEnterprise, user);
                            projectEnterpriseList.add(projectEnterprise);
                            List<ProjectMaintainStaff> staffs = enterprise.getStaffList();
                            if (staffs != null && staffs.size() > 0) {
                                for (ProjectMaintainStaff staff : staffs) {
                                    if (StringUtils.isBlank(staff.getStaffCode()) || StringUtils.isBlank(staff.getStaffName())) {
                                        msg.setCode(BusinessCode.PROJECT_MAINTAIN_STAFF_CANNOT_EMPTY.getCode());
                                        msg.setDescription(BusinessCode.PROJECT_MAINTAIN_STAFF_CANNOT_EMPTY.getDescription());
                                        return msg;
                                    }
                                    staff.setEnterpriseId(enterprise.getId());
                                    staff.setProjectId(project.getId());
                                    BaseEntityUtil.setAddBaseProperties(staff, user);
                                    projectMaintainStaffList.add(staff);
                                }
                            }
                        }
                    }
                }
            }
            //保存附件
            String[] keepAddressArray = StringUtils.isEmpty(keepPathListStr) ? null : keepPathListStr.split("[,，]");
            String[] keepPreAddressArray = StringUtils.isEmpty(keepPrePathListStr) ? null : keepPrePathListStr.split("[,，]");

            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (keepAddressArray != null && keepAddressArray.length > 0) {
                keepAddressList = Arrays.asList(keepAddressArray).stream().collect(Collectors.toList());
            }
            if (keepPreAddressArray != null && keepPreAddressArray.length > 0) {
                keepPreAddressList = Arrays.asList(keepPreAddressArray).stream().collect(Collectors.toList());
            }
            if (files != null && files.length > 0) {
                List<String> pathList = new ArrayList<>();
                for (MultipartFile file : files) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(file);
                        String filPath = url + "#" + file.getOriginalFilename();
                        keepAddressList.add(filPath);
//                        File pdfFile = DocConverterUtils.converter(file);
                        String pdfPath = docConverterUtils.converterUpdate(file);

                        if (pdfPath != null) {
//                            String pdfFilePath = clientWrapper.uploadFile(new FileInputStream(pdfFile), pdfFile.length(), FilenameUtils.getExtension(pdfFile.getName()));
                            keepPreAddressList.add(pdfPath);
                        } else {
                            keepPreAddressList.add(filPath);
                        }
                    }
                }
            }
            project.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            project.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            projectMapper.updateByPrimaryKeySelective(project);

            List<ProjectEnterprise> peList = projectEnterpriseMapper.selectByProjectId(projectId);
            List<ProjectEnterprise> delProjectEnterpriseList = new ArrayList<>();
            //删除原来项目的相关方
            projectEnterpriseMapper.deleteByProjectId(project.getId());
            if (projectEnterpriseList != null && projectEnterpriseList.size() > 0) {
                if (peList != null && !peList.isEmpty()) {
                    peList.stream().forEach(pe -> {
                        if (!projectEnterpriseList.stream().anyMatch(peSave -> peSave.getEnterpriseId().equals(pe.getEnterpriseId()
                        ) && peSave.getProjectId().equals(pe.getProjectId()))) {
                            delProjectEnterpriseList.add(pe);
                        }
                    });
                }
                //保存
                projectEnterpriseMapper.insertList(projectEnterpriseList);
            } else {
                delProjectEnterpriseList.addAll(peList);
            }
            //处理需要删除的相关方信息
            if (delProjectEnterpriseList != null && !delProjectEnterpriseList.isEmpty()) {
                ProjectTrainingMapper trainingMapper = factory.getMapper(ProjectTrainingMapper.class);
                ProjectStaffMapper staffMapper = factory.getMapper(ProjectStaffMapper.class);
                ProjectCertificateMapper certificateMapper = factory.getMapper(ProjectCertificateMapper.class);
                ProjectHazardSourceMapper hazardSourceMapper = factory.getMapper(ProjectHazardSourceMapper.class);
                ProjectSafetyInvestmentMapper safetyInvestmentMapper = factory.getMapper(ProjectSafetyInvestmentMapper.class);
                ProjectSafetyMeetingMapper meetingMapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
                ProjectFileMapper fileMapper = factory.getMapper(ProjectFileMapper.class);
                ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
                for (ProjectEnterprise pe : delProjectEnterpriseList) {
                    trainingMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    staffMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    certificateMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    hazardSourceMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    safetyInvestmentMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    meetingMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    fileMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                    assessmentMapper.deleteByProjectAndEnterprise(pe.getProjectId(), pe.getEnterpriseId());
                }
            }
            //删除原项目维护人员
            maintainStaffMapper.deleteByProjectId(project.getId());
            if (projectMaintainStaffList != null && projectMaintainStaffList.size() > 0) {
                maintainStaffMapper.insertList(projectMaintainStaffList);
            }

            //删除去除的附件
            if (StringUtils.isNotEmpty(deletePathListStr)) {
                String[] delArray = deletePathListStr.split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
            //删除去除的附件
            if (StringUtils.isNotEmpty(deletePrePathListStr)) {
                String[] delArray = deletePrePathListStr.split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    void setProperties(List<Project> projectList, EnterpriseMapper enterpriseMapper, ProjectMaintainStaffMapper maintainStaffMapper) {
        for (Project project : projectList) {
            if (project != null && StringUtils.isNotBlank(project.getId())) {
                //项目相关方
                List<Enterprise> enterpriseList = enterpriseMapper.queryListByProjectId(project.getId());
                if (enterpriseList != null && enterpriseList.size() > 0) {
                    for (Enterprise enterprise : enterpriseList) {
                        if (StringUtils.isNotBlank(enterprise.getId())) {
                            //维护人员
                            List<ProjectMaintainStaff> staffs = maintainStaffMapper.queryListByProjectEnterprise(project.getId(), enterprise.getId());
                            enterprise.setStaffList(staffs);
                        }
                    }
                }
                project.setEnterpriseList(enterpriseList);
            }
        }
    }

    @Override
    public MessageBean<?> list(StaffBean user, String name, String projectType, Integer state, String corpCode,
                               String projectId, String enterpriseId,String keyword, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            EnterpriseMapper enterpriseMapper = factory.getMapper(EnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            String codes = util.getDeptCodes(corpCode);
            List<Project> projectList = projectMapper.queryList(name, projectType, state, codes, projectId, start, pageSize,keyword);
            int total = projectMapper.queryListTotal(name, projectType, state, codes, projectId,keyword);
//            if (projectList != null && projectList.size() > 0) {
//                //处理相关方和维护人员
//                setProperties(projectList, enterpriseMapper, maintainStaffMapper);
//            }
            DataBean dataBean = new DataBean();
            dataBean.setList(projectList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> delete(StaffBean user, String projectId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (StringUtils.isBlank(projectId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            ProjectEnterpriseMapper projectEnterpriseMapper = factory.getMapper(ProjectEnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            //查询是否存在关联,是否能删除
            List<ProjectEnterprise> list = projectEnterpriseMapper.selectByProjectId(projectId);
            if (list != null && !list.isEmpty()) {
                msg.setCode(BusinessCode.PROJECT_EXIST_ENTERPRISE.getCode());
                msg.setDescription(BusinessCode.PROJECT_EXIST_ENTERPRISE.getDescription());
                return msg;
            }
            Project project = projectMapper.selectByPrimaryKey(projectId);
            if (project != null) {
                if (StringUtils.isNotBlank(project.getAttachment())) {
                    List<String> pathList = JSONObject.parseArray(project.getAttachment(), String.class);
                    if (pathList != null && !pathList.isEmpty()) {
                        for (String p : pathList) {
                            clientWrapper.deleteFile(p.split("#")[0]);
                        }
                    }
                }
                if (StringUtils.isNotBlank(project.getPreviewAttachment())) {
                    List<String> pathList = JSONObject.parseArray(project.getPreviewAttachment(), String.class);
                    if (pathList != null && !pathList.isEmpty()) {
                        for (String p : pathList) {
                            clientWrapper.deleteFile(p.split("#")[0]);
                        }
                    }
                }
            }
            projectEnterpriseMapper.deleteByProjectId(projectId);
            maintainStaffMapper.deleteByProjectId(projectId);
            projectMapper.deleteByPrimaryKey(projectId);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }


    @Override
    public MessageBean<?> deleteEnterprise(StaffBean user, String projectId, String enterpriseId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (StringUtils.isBlank(projectId) || StringUtils.isBlank(enterpriseId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ProjectTrainingMapper trainingMapper = factory.getMapper(ProjectTrainingMapper.class);
            ProjectStaffMapper staffMapper = factory.getMapper(ProjectStaffMapper.class);
            ProjectCertificateMapper certificateMapper = factory.getMapper(ProjectCertificateMapper.class);
            ProjectHazardSourceMapper hazardSourceMapper = factory.getMapper(ProjectHazardSourceMapper.class);
            ProjectSafetyInvestmentMapper safetyInvestmentMapper = factory.getMapper(ProjectSafetyInvestmentMapper.class);
            ProjectSafetyMeetingMapper meetingMapper = factory.getMapper(ProjectSafetyMeetingMapper.class);
            ProjectFileMapper fileMapper = factory.getMapper(ProjectFileMapper.class);
            ProjectAssessmentMapper assessmentMapper = factory.getMapper(ProjectAssessmentMapper.class);
            trainingMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            staffMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            certificateMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            hazardSourceMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            safetyInvestmentMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            meetingMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            fileMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
            assessmentMapper.deleteByProjectAndEnterprise(projectId, enterpriseId);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> projectEnterpriseList(StaffBean user, String enterpriseName, String projectName, String corpCode,String keyword, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectEnterpriseMapper projectEnterpriseMapper = factory.getMapper(ProjectEnterpriseMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            String codes = util.getDeptCodes(corpCode);
            List<ProjectEnterprise> projectEnterpriseList = projectEnterpriseMapper.projectEnterpriseList(projectName, enterpriseName, codes,keyword , start, pageSize);
            int total = projectEnterpriseMapper.projectEnterpriseListTotal(projectName, enterpriseName, codes,keyword);
            DataBean dataBean = new DataBean();
            dataBean.setList(projectEnterpriseList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> detail(StaffBean user, String projectId) {
        MessageBean<Project> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Project.class);
        if (StringUtils.isBlank(projectId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            EnterpriseMapper enterpriseMapper = factory.getMapper(EnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            Project project = projectMapper.selectByPrimaryKey(projectId);
            if (project != null) {
                List<Enterprise> enterpriseList = enterpriseMapper.queryListByProjectId(project.getId());
                if (enterpriseList != null && enterpriseList.size() > 0) {
                    for (Enterprise enterprise : enterpriseList) {
                        if (StringUtils.isNotBlank(enterprise.getId())) {
                            //维护人员
                            List<ProjectMaintainStaff> staffs = maintainStaffMapper.queryListByProjectEnterprise(project.getId(), enterprise.getId());
                            enterprise.setStaffList(staffs);
                        }
                    }
                }
                project.setEnterpriseList(enterpriseList);
            }
            msg.setData(project);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> importExcel(StaffBean user, MultipartFile file) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "导入成功", String.class);
        SessionFactory factory = new SessionFactory();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Project> list = new ArrayList<>();
        try {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                msg.setCode(BusinessCode.FAILURE.getCode());
                return msg;
            }
            // 获取excel表格行数
            int rows = sheet.getPhysicalNumberOfRows();
            // 从第二行开始读取数据
            for (int i = 2; i < rows; i++) {
                Project project = new Project();
                XSSFRow row = sheet.getRow(i);
                String name = getCellValue(row.getCell(0));
                String corpName = getCellValue(row.getCell(1));
                String projectType = getCellValue(row.getCell(2));
                String projectLeaderName = getCellValue(row.getCell(3));
                String establishDate = getCellValue(row.getCell(4));
                String state = getCellValue(row.getCell(5));
                String description = getCellValue(row.getCell(6));
                if (StringUtils.isNotEmpty(name)) {
                    project.setName(name);
                }
                if (StringUtils.isNotEmpty(corpName)) {
                    project.setCorpName(corpName);
                }
                if (StringUtils.isNotEmpty(projectType)) {
                    project.setProjectType(("在建工程").equals(projectType) ? "0" : ("零散工程").equals(projectType) ? "1" : null);
                }
                if (StringUtils.isNotEmpty(projectLeaderName)) {
                    project.setProjectLeaderName(projectLeaderName);
                }
                if (StringUtils.isNotEmpty(establishDate)) {
                    Date date = null;
                    try {
                        // 如果excel中为文本格式，且符合yyyy-MM-dd格式，直接转换成Date类型
                        date = sdf.parse(establishDate);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    } finally {
                        if (null == date) {
                            // 转换失败，默认excel中为日期格式
                            date = HSSFDateUtil.getJavaDate(Double.parseDouble(establishDate));
                        }
                    }
                    if (null != date) {
                        project.setEstablishDate(date);
                    }
                }
                if (StringUtils.isNotEmpty(state)) {
                    if (("在建").equals(state)) {
                        project.setState(0);
                    } else if (("完工").equals(state)) {
                        project.setState(1);
                    }
                }
                if (StringUtils.isNotEmpty(description)) {
                    project.setDescription(description);
                }
                if (!checkObjAllFieldsIsNull(project)) {
                    list.add(project);
                }
            }
            // 获取组织架构
            MessageBean<?> orgTree = util.getOrgTree();
            List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) orgTree.getData();
            if (list.size() > 0) {
                for (Project bean : list) {
                    if (StringUtils.isNotEmpty(bean.getCorpName())) {
                        //如果建设单位不为空，则根据建设单位名称过滤,如果能匹配到单位，就取匹配到的单位
                        List<DepartmentTreeBean> treeBeanList = departmentTreeBeanList.stream().filter(departmentTreeBean -> bean.getCorpName().equals(departmentTreeBean.getName())).collect(Collectors.toList());
                        if (null != treeBeanList && treeBeanList.size() > 0) {
                            bean.setCorpCode(treeBeanList.get(0).getDepartmentCode());
                        } else {
                            // 如果匹配不到单位，就取当前登录人所在的单位
                            bean.setCorpCode(user.getDepartmentCode());
                        }
                    } else {
                        //如果建设单位为空,则默认当前操作人所在单位为建设单位
                        bean.setCorpCode(user.getDepartmentCode());
                        bean.setCorpName(user.getDepartmentname());
                    }
                    // 如果项目负责人名称不为空，则根据项目负责人名称查询人员信息
                    if (StringUtils.isNotEmpty(bean.getProjectLeaderName())) {
                        Map map = (Map) util.getStaffAndDeptFuzzyQuery(bean.getProjectLeaderName()).getData();
                        List<StaffBean> staffs = (List<StaffBean>) map.get("staffs");
                        if (null != staffs && staffs.size() > 0) {
                            bean.setProjectLeaderCode(staffs.get(0).getCode());
                        }
                    } else {
                        // 如果项目负责人名称为空，则默认当前操作人为项目负责人
                        bean.setProjectLeaderCode(user.getCode());
                        bean.setProjectLeaderName(user.getName());
                    }
                    bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                    bean.setAddUser(user.getCode());
                    bean.setAddUserName(user.getName());
                    bean.setAddTime(new Date());
                }
                Integer integer = factory.getMapper(ProjectMapper.class).batchInsert(list);
                if (integer <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    return msg;
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("导入失败");
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @Override
    public List<Project> exportList(StaffBean user, String corpCode, String name, String projectType, Integer state, String projectId, String enterpriseId) {
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            EnterpriseMapper enterpriseMapper = factory.getMapper(EnterpriseMapper.class);
            ProjectMaintainStaffMapper maintainStaffMapper = factory.getMapper(ProjectMaintainStaffMapper.class);
            String codes = util.getDeptCodes(corpCode);
            List<Project> projectList = projectMapper.queryList(name, projectType, state, codes, projectId, null, null,null);
            if (projectList != null && projectList.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                //处理相关方和维护人员
//                setProperties(projectList, enterpriseMapper, maintainStaffMapper);
                projectList.forEach(bean -> {
                    if (null != bean.getEstablishDate()) {
                        bean.setEstablishDateStr(sdf.format(bean.getEstablishDate()));
                    }
                    if (StringUtils.isNotEmpty(bean.getProjectType())) {
                        if ("0".equals(bean.getProjectType())) {
                            bean.setProjectType("在建工程");
                        } else if ("1".equals(bean.getProjectType())) {
                            bean.setProjectType("零散工程");
                        }
                    }
                });
            }
            return projectList;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @Override
    public List<ProjectEnterpriseVo> exportProjectEnterpriseList(StaffBean user, String enterpriseName, String projectName, String corpCode) {
        try (SessionFactory factory = new SessionFactory()) {
            ProjectEnterpriseMapper projectEnterpriseMapper = factory.getMapper(ProjectEnterpriseMapper.class);
            String codes = util.getDeptCodes(corpCode);
            List<ProjectEnterpriseVo> list = projectEnterpriseMapper.exportProjectEnterpriseList(projectName, enterpriseName, codes);
            if (null != list && list.size() > 0) {
                list.forEach(bean -> {

                    if (StringUtils.isNotEmpty(bean.getEnterpriseType())) {
                        if ("0".equals(bean.getEnterpriseType())) {
                            bean.setEnterpriseType("施工方");
                        } else if ("1".equals(bean.getEnterpriseType())) {
                            bean.setEnterpriseType("监理方");
                        }
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }

    }

    @Override
    public MessageBean<?> getAll(StaffBean user) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            List<Project> projectList = projectMapper.getAllProject();
            msg.setData(projectList);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> homePageProjectList(StaffBean user, String name, String projectType, Integer state, String corpCode, String projectId, String enterpriseId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectMapper projectMapper = factory.getMapper(ProjectMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            String codes = util.getDeptCodes(corpCode);
            List<Project> projectList = projectMapper.homePageProjectList(name, projectType, state, codes, projectId, start, pageSize);
            int total = projectMapper.homePageProjectCount(name, projectType, state, codes, projectId);
            DataBean dataBean = new DataBean();
            dataBean.setList(projectList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }
}
